package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
	"time"
)

//自定义注册验证

type Booking struct {
	//注意：tag字段中不能出现空格，否则会报错
	CheckIn time.Time `form:"check_in" binding:"required,bookableDate" time_format:"2006-01-02"`
	CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
}

func bookableDate(f validator.FieldLevel) bool {
	if date,ok := f.Field().Interface().(time.Time);ok{
		today := time.Now()
		if date.Unix()>today.Unix(){
			return true
		}else {
			return false
		}
	}
	return false
}

func main(){

	engine := gin.Default()

	if v,ok := binding.Validator.Engine().(*validator.Validate);ok{
		//注册验证
		err := v.RegisterValidation("bookableDate", bookableDate)
		if err != nil {
			return
		}
	}

	engine.GET("/bookable", func(c *gin.Context) {
		var booking Booking
		if err := c.ShouldBindWith(&booking,binding.Query); err != nil {
			c.JSON(500,gin.H{
				"error" : err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK,gin.H{"message":"ok!","booking":booking})
	})
	engine.Run(":8090")
}
